<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryFormRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="门店" prop="shopId">
        <el-select
          v-model="queryParams.shopId"
          placeholder="请选择门店"
          clearable
          filterable
          style="width: 240px"
          :loading="loadingShops"
          @change="handleQuery"
        >
          <el-option
            v-for="shop in shopOptions"
            :key="shop.id"
            :label="shop.shopName"
            :value="shop.id"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
        <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="list">
      <el-table-column label="序号" type="index" width="70" :index="indexMethod" align="center" />
      <el-table-column label="用户名" prop="nickName" align="center" />
      <el-table-column label="绑定手机号" prop="phonenumber" align="center" />
      <el-table-column label="所属门店" prop="sourceShop" align="center">
        <template #default="scope">
          {{ formatShopNames(scope.row.sourceShop) }}
        </template>
      </el-table-column>
      <el-table-column label="技师等级" prop="consultantRankName" align="center" />
      <el-table-column label="是否推广用户" prop="inviteFlag" align="center">
        <template #default="scope">
          {{ (sysYesNo.find(i => i.value === String(scope.row.inviteFlag)) || {}).label || scope.row.inviteFlag }}
        </template>
      </el-table-column>
      <el-table-column label="用户状态" prop="status" align="center">
        <template #default="scope">
          {{ String(scope.row.status) === '0' ? '正常' : '停用' }}
        </template>
      </el-table-column>
      <el-table-column label="注册时间" prop="createTime" align="center">
        <template #default="scope">
          {{ parseTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button type="text" @click="handleView(scope.row)">详请</el-button>
          <el-button type="text" @click="handleSetRank(scope.row)">设定顾问等级</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      v-model:total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog v-model="viewOpen" width="500px" title="顾问详情" append-to-body>
      <el-descriptions :column="1" v-if="current">
        <el-descriptions-item label="用户名">{{ current.nickName }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ current.phonenumber }}</el-descriptions-item>
        <el-descriptions-item label="所属门店">{{ formatShopNames(current?.sourceShop) }}</el-descriptions-item>
        <el-descriptions-item label="等级">{{ current.consultantRankName }}</el-descriptions-item>
        <el-descriptions-item label="推广用户">{{ (sysYesNo.find(i => i.value === String(current.inviteFlag)) || {}).label || current.inviteFlag }}</el-descriptions-item>
        <el-descriptions-item label="状态">{{ String(current.status) === '0' ? '正常' : '停用' }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewOpen=false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="rankOpen" width="420px" title="设定顾问等级" append-to-body>
      <el-form :model="rankForm" ref="rankFormRef" label-width="90px">
        <el-form-item label="顾问姓名">
          <span>{{ current?.nickName || current?.userName }}</span>
        </el-form-item>
        <el-form-item label="技师等级" prop="consultantRankId" required>
          <el-select v-model="rankForm.consultantRankId" placeholder="请选择" filterable style="width: 100%">
            <el-option v-for="r in rankOptions" :key="r.value" :label="r.label" :value="r.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitRank">确 定</el-button>
          <el-button @click="rankOpen=false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ConsultantIndex">
import { ref, reactive, toRefs, onMounted } from 'vue'
import { Search, Refresh } from '@element-plus/icons-vue'
import { listConsultants, updateConsultantRank } from "@/api/system/consultant"
import { listShopItem } from "@/api/system/shopIndex"
import { listRank } from "@/api/system/rank"
import { ElMessage } from 'element-plus'
import { parseTime } from '@/utils/ruoyi'
import { getsysYesNo } from '@/api/system/goodType'

// Refs
const queryFormRef = ref()
const rankFormRef = ref()
const shopOptions = ref([])
const loadingShops = ref(false)
const sysYesNo = ref([])
const rankOptions = ref([])

// State
const state = reactive({
  loading: false,
  total: 0,
  list: [],
  showSearch: true,
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    shopId: undefined
  },
  viewOpen: false,
  rankOpen: false,
  current: null,
  rankForm: {}
})

const { loading, total, list, showSearch, queryParams, viewOpen, rankOpen } = toRefs(state)
const current = toRefs(state).current
const rankForm = toRefs(state).rankForm

// Methods
const indexMethod = (index) => {
  return (queryParams.value.pageNum - 1) * queryParams.value.pageSize + index + 1
}

const getList = () => {
  loading.value = true
  listConsultants(queryParams.value).then(res => {
    list.value = res.rows || []
    total.value = res.total || 0
  }).finally(() => loading.value = false)
}

const handleQuery = () => {
  queryParams.value.pageNum = 1
  getList()
}

const resetQuery = () => {
  queryFormRef.value?.resetFields()
  queryParams.value.shopId = undefined
  handleQuery()
}

const handleView = (row) => {
  state.current = row
  state.viewOpen = true
}

const handleSetRank = (row) => {
  state.current = row
  state.rankForm = { consultantRankId: undefined }
  loadRanks().then(() => {
    if (row.consultantRank) {
      state.rankForm.consultantRankId = String(row.consultantRank)
    } else if (row.consultantRankName) {
      const m = rankOptions.value.find(r => r.label === row.consultantRankName)
      state.rankForm.consultantRankId = m?.value
    }
    state.rankOpen = true
  })
}

const submitRank = () => {
  const userId = state.current?.userId
  const consultantRankId = rankForm.value.consultantRankId
  if (!userId || !consultantRankId) {
    state.rankOpen = false
    return
  }
  const rankItem = rankOptions.value.find(r => r.value === consultantRankId)
  const payload = { 
    ...(state.current || {}), 
    userId, 
    consultantRank: consultantRankId, 
    consultantRankName: rankItem?.label 
  }
  updateConsultantRank(payload).then(() => {
    state.rankOpen = false
    getList()
  }).catch(() => {
    state.rankOpen = false
  })
}

// Data loading functions
const loadDicts = () => {
  return getsysYesNo().then(res => {
    const arr = res?.data || []
    sysYesNo.value = arr.map(p => ({ 
      label: p.dictLabel, 
      value: String(p.dictValue) 
    }))
  }).catch(() => sysYesNo.value = [])
}

const loadShops = () => {
  loadingShops.value = true
  return listShopItem({ pageNum: 1, pageSize: 999 })
    .then(res => {
      if (res?.code === 200 && res.rows?.length) {
        shopOptions.value = res.rows
      }
    })
    .catch(error => {
      console.error('加载门店列表失败:', error)
      ElMessage.error('加载门店列表失败')
    })
    .finally(() => {
      loadingShops.value = false
    })
}

const loadRanks = () => {
  return listRank({ pageNum: 1, pageSize: 999 })
    .then(res => {
      const rows = res?.rows || []
      rankOptions.value = rows.map(r => ({
        label: r.levelName,
        value: String(r.levelId)
      }))
    })
    .catch(error => {
      console.error('加载等级列表失败:', error)
      ElMessage.error('加载等级列表失败')
    })
}

// Helper functions
const getShopName = (shopId) => {
  if (!shopId) return '--'
  const shop = shopOptions.value.find(s => s.id === shopId)
  return shop ? shop.shopName : shopId
}

// 格式化门店名称，处理多个门店ID用逗号分隔的情况
const formatShopNames = (sourceShop) => {
  if (!sourceShop) return '--'
  const shopIds = String(sourceShop).split(',').filter(Boolean)
  return shopIds.map(id => {
    // 先尝试直接匹配ID
    const shopById = shopOptions.value.find(s => s.id === id)
    if (shopById) return shopById.shopName
    
    // 如果没有找到，尝试将ID转为数字再匹配（处理可能的类型不一致）
    const numId = Number(id)
    if (!isNaN(numId)) {
      const shopByNumId = shopOptions.value.find(s => s.id === numId)
      if (shopByNumId) return shopByNumId.shopName
    }
    
    // 如果还是没找到，返回ID
    return id
  }).join('、') || '--'
}

// Lifecycle
onMounted(async () => {
  try {
    await Promise.all([
      loadDicts(),
      loadShops(),
      loadRanks()
    ])
    getList()
  } catch (error) {
    console.error('初始化失败:', error)
    ElMessage.error('初始化数据失败')
  }
})
</script>
